package cc.mrbird.febs.accounting.service.impl;

import cc.mrbird.febs.accounting.dto.standardSub.SingleExportDTO;
import cc.mrbird.febs.accounting.entity.*;
import cc.mrbird.febs.accounting.mapper.EstimateHistoryMapper;
import cc.mrbird.febs.accounting.mapper.MainCostMapper;
import cc.mrbird.febs.accounting.service.IDetailCostService;
import cc.mrbird.febs.accounting.service.IEstimateHistoryService;
import cc.mrbird.febs.accounting.service.IMainCostService;
import cc.mrbird.febs.accounting.service.IProjectService;
import cc.mrbird.febs.utils.ArithUtil;
import cc.mrbird.febs.utils.CodeConstant;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.utils.DetailCostUtil;
import cc.mrbird.febs.utils.PermissionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 *  Service实现
 *
 * @author hbh
 * @date 2021-09-28 23:07:50
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EstimateHistoryServiceImpl extends ServiceImpl<EstimateHistoryMapper, EstimateHistory> implements IEstimateHistoryService {

    @Resource
    private IProjectService projectService;
    @Resource
    private IMainCostService mainCostService;
    @Resource
    private IDetailCostService detailCostService;
    @Resource
    private DetailCostUtil detailCostUtil;

    @Override
    public List<EstimateHistory> queryByYearMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)-1);
        int year = cal.get(Calendar.YEAR);
        int lastMonth = cal.get(Calendar.MONTH )+1;
        String monthString = lastMonth < 10 ? "0" + lastMonth :lastMonth + "";
        String yearMonth = year + "-" + monthString;
        LambdaQueryWrapper<EstimateHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EstimateHistory::getIsDeleted, 0);
        queryWrapper.eq(EstimateHistory::getYearMonth, yearMonth);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<EstimateHistory> queryByYear(String year) {
        return this.baseMapper.queryByYear(year);
    }

    @Override
    public void confirm(String year, String lastMonth) {
        List<String> yearMonths = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String month = i < 10 ? "0" + i + "" : i + "";
            yearMonths.add(year + "-" + month);
        }
        String monthString = Integer.parseInt(lastMonth) < 10 ? "0" + lastMonth :lastMonth;
        String yearMonth = year + "-" + monthString;
        List<EstimateHistory> estimateHistories = new ArrayList<>();
        List<Project> projects = this.projectService.findProjects(null);
        Map<String, BigDecimal> idColCostMap = new HashMap<>();
        projects.forEach(e -> {
            // todook
            // List<SingleExportDTO> singleExportDTOs = this.detailCostService.queryDetailForExcel(e.getId(), year+"", yearMonths).getSingleExportDTOS();
            List<SingleExportDTO> singleExportDTOs = detailCostUtil.getMergedSingleExport(e.getId(), year+"", yearMonths).getSingleExportDTOS();
            String[] sub1 = {"项目年终奖金/年终活动经费预算/其他（预提）", "年终奖金预提（管理）", "每月实发工资（项目）"};
            String[] sub2 = {"项目年终奖金/年终活动经费预算/其他（预提）", "年终奖金预提（管理）", "每月应发工资（项目）",
                    "实际社会保险单位", "公积金单位（项目）"};
            String[] sub;
            if (e.getProjectCity().trim().equals("杭州")) {
                sub = sub1;
            } else {
                sub = sub2;
            }
            singleExportDTOs.forEach(r -> {
                String subjectTitle = "";
                if (r.getSubName().equals("拓天项目收入") && r.getYearMonth().equals(yearMonth)) {
                    subjectTitle = "收入";
                    String key = subjectTitle + "-" + e.getId() + "-" + r.getYearMonth().split("-")[1];
                    idColCostMap.put(key, r.getCost());
                } else if (r.getSubName().equals("费用合计") && r.getYearMonth().equals(yearMonth)) {
                    subjectTitle = "费用";
                    String key = subjectTitle + "-" + e.getId() + "-" + r.getYearMonth().split("-")[1];
                    idColCostMap.put(key, r.getCost());
                } else if (r.getSubName().equals("月总人数（包括离职和新员工）") && r.getYearMonth().equals(yearMonth)) {
                    subjectTitle = "员工人数";
                    String key = subjectTitle + "-" + r.getYearMonth().split("-")[1];
                    idColCostMap.put(key, idColCostMap.getOrDefault(key, new BigDecimal("0.00")).add(r.getCost()));
                }
                if (Arrays.asList(sub).contains(r.getSubName()) && r.getYearMonth().equals(yearMonth)) {
                    subjectTitle = "成本";
                    String key = subjectTitle + "-" + e.getId() + "-" + r.getYearMonth().split("-")[1];
                    idColCostMap.put(key, idColCostMap.getOrDefault(key, new BigDecimal("0.00")).add(r.getCost()));
                }
            });
        });
        LambdaQueryWrapper<MainCost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MainCost::getYearMonth, yearMonth);
        queryWrapper.eq(MainCost::getIsDeleted, 0);
        List<MainCost> mainCosts = this.mainCostService.getBaseMapper().selectList(queryWrapper);
        for (MainCost e : mainCosts) {
            String key = e.getDetailSubjectCode() + "-" + e.getYearMonth().split("-")[1];
            EstimateHistory estimateHistory = new EstimateHistory();
            estimateHistory.setKey(key);
            estimateHistory.setCost(e.getCost());
            estimateHistory.setIsDeleted(0);
            estimateHistory.setRemark(e.getRemark());
            estimateHistory.setCreateBy(FebsUtil.getCurrentUser().getUsername());
            estimateHistory.setCreateTime(new Date());
            estimateHistory.setYearMonth(yearMonth);
            estimateHistories.add(estimateHistory);
        }

        // 添加增值税进项
        LambdaQueryWrapper<DetailCost> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(DetailCost::getYearMonth, yearMonth);
        queryWrapper2.eq(DetailCost::getIsDeleted, 0);
        List<DetailCost> detailCosts = this.detailCostService.getBaseMapper().selectList(queryWrapper2);
        double inputTaxAdjustCost = 0.0;
        for (DetailCost e : detailCosts) {
            if (e.getInputTaxAdjustment() !=null ) {
                inputTaxAdjustCost = ArithUtil.add(inputTaxAdjustCost, e.getInputTaxAdjustment().doubleValue());
            }
        }

        String key = CodeConstant.inputTaxAdjustment + "-" + yearMonth.split("-")[1];
        EstimateHistory inputTaxAdjustment = new EstimateHistory();
        inputTaxAdjustment.setKey(key);
        inputTaxAdjustment.setCost(new BigDecimal(inputTaxAdjustCost));
        inputTaxAdjustment.setIsDeleted(0);
        inputTaxAdjustment.setCreateBy(FebsUtil.getCurrentUser().getUsername());
        inputTaxAdjustment.setCreateTime(new Date());
        inputTaxAdjustment.setYearMonth(yearMonth);
        estimateHistories.add(inputTaxAdjustment);

        for (Map.Entry<String, BigDecimal> entry : idColCostMap.entrySet()) {
            EstimateHistory estimateHistory = new EstimateHistory();
            estimateHistory.setKey(entry.getKey());
            estimateHistory.setCost(entry.getValue());
            estimateHistory.setIsDeleted(0);
            estimateHistory.setCreateBy(FebsUtil.getCurrentUser().getUsername());
            estimateHistory.setCreateTime(new Date());
            estimateHistory.setYearMonth(yearMonth);
            estimateHistories.add(estimateHistory);
        }
        LambdaQueryWrapper<EstimateHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EstimateHistory::getYearMonth, yearMonth);
        this.remove(wrapper);
        this.saveBatch(estimateHistories);
    }

    @Override
    public List<String> queryConfirmed() {
        return this.baseMapper.queryConfirmed();
    }
}
